﻿Imports Models.Solution
Imports System.ComponentModel.DataAnnotations
Imports Models.Security

Public Class UserSolutions
    Inherits BaseService

    Sub New(request As System.Net.Http.HttpRequestMessage)
        Me.loadToken(request)
    End Sub
    Sub New(token As String)
        Me.token = token
    End Sub

    ''' <summary>
    ''' Gets the specified id.
    ''' </summary>
    ''' <param name="id">The id.</param>
    ''' <returns></returns>
    Public Function [Get](id As Integer) As UserSolutionVO
        Try
            Me.checkAccess("GETUSERSOLUTION")
            Dim oEntity As UserSolutionVO

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")
                Dim oDataEntity As Data.BaseModel.UserSolution = (From u In oDB.UserSolutions Where u.UserSolutionId = id Select u).FirstOrDefault()

                If oDataEntity IsNot Nothing Then
                    oEntity = New UserSolutionVO(oDataEntity)
                End If
            End Using

            Return oEntity

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
        End Try


    End Function

    ' ''' <summary>
    ' ''' Gets the specified login.
    ' ''' </summary>
    ' ''' <param name="login">The id.</param>
    ' ''' <returns></returns>
    'Public Function [Get](login As String) As UserVO
    '    Try
    '        '' Sin permisos y sin controller. Creado para acceder al User en el startup del proyecto FastPath
    '        Dim oEntity As UserVO

    '        Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")
    '            Dim oDataEntity As Data.BaseModel.User = (From u In oDB.Users Where u.UserLogin = login Select u).FirstOrDefault()

    '            If oDataEntity IsNot Nothing Then
    '                oEntity = New UserVO(oDataEntity)
    '            End If
    '        End Using

    '        Return oEntity

    '    Catch ex As Exception
    '        MainLib.Helpers.ExceptionWrapper(ex)
    '    End Try

    'End Function


    ''' <summary>
    ''' Get List of User Solutions
    ''' </summary>
    ''' <param name="userCompanyId">optional for filter</param>
    ''' <returns>Array of Solutions</returns>
    ''' <remarks>Chequear si falta traer algo</remarks>
    Public Function List(Optional userCompanyId As Integer = -1) As IEnumerable(Of UserSolutionVO)
        Try
            Me.checkAccess("LISTUSERSOLUTIONS")
            Dim oResult As New Generic.List(Of UserSolutionVO)
            Dim oDataEntity As New Generic.List(Of Data.BaseModel.UserSolution)

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")
                If userCompanyId = -1 Then
                    oDataEntity = oDB.UserSolutions.ToList()
                Else
                    Dim oUser As Data.BaseModel.UserCompany = (From c In oDB.UserCompanies Where c.UserCompanyId = userCompanyId Select c).FirstOrDefault

                    'oDataEntity = oUser.UserSolutions
                    For Each oUserSolution As Data.BaseModel.UserSolution In oUser.UserSolutions
                        oDataEntity.Add(oUserSolution)
                    Next
                    'Dim oList2 As Generic.List(Of Data.BaseModel.UserSolution) = (From c In oDB.UserSolutions Where c.UserId = userId Select c).ToList()
                End If

                'oDataEntity = oDB.UserSolutions.ToList()
                'If Not SolutionId = -1 Then
                '    Dim oListUserComp As New Generic.List(Of Data.BaseModel.UserSolution)
                '    Dim query As IQueryable(Of Data.BaseModel.UserSolution) = From c In oDB.UserSolutions Where c.SolutionId = SolutionId Select c
                '    oListUserComp = query.ToList()
                '    Dim oDataAux As New Generic.List(Of Data.BaseModel.User)
                '    oDataAux.AddRange(oDataEntity)
                '    For Each oItemUser As Data.BaseModel.User In oDataEntity
                '        For Each oItemUserComp As Data.BaseModel.UserSolution In oListUserComp
                '            If oItemUser.UserId = oItemUserComp.UserId Then
                '                Exit For
                '            ElseIf oItemUserComp Is oListUserComp.Last Then
                '                '' Sino esta en la lista, lo saca
                '                oDataAux.Remove(oItemUser)
                '            End If
                '        Next
                '    Next
                '    oDataEntity.Clear()
                '    oDataEntity.AddRange(oDataAux)
                'End If

                If oDataEntity IsNot Nothing Then
                    For Each dbData As Data.BaseModel.UserSolution In oDataEntity
                        oResult.Add(New UserSolutionVO(dbData))
                    Next
                End If

            End Using

            Return oResult

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
        End Try
    End Function

    ''' <summary>
    ''' Update a User Solution
    ''' </summary>
    ''' <param name="userSolution"></param>
    ''' <returns></returns>
    ''' <remarks>Incompleto</remarks>
    Public Function Update(userSolution As UserSolutionVO) As Integer
        Try
            Me.checkAccess("UPDATEUSERSOLUTION")
            Dim nRes As Integer = -1

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim oData As Data.BaseModel.UserSolution = (From c In oDB.UserSolutions Where c.UserSolutionId = userSolution.userSolutionId Select c).FirstOrDefault()

                If oData IsNot Nothing Then

                    If Not String.IsNullOrEmpty(userSolution.solutionId) Then
                        oData.SolutionId = userSolution.solutionId
                    End If
                    If Not String.IsNullOrEmpty(userSolution.permissionId) Then
                        oData.PermissionId = userSolution.permissionId
                    End If

                    If userSolution.solution IsNot Nothing AndAlso Boolean.TryParse(userSolution.solution.deleted, True) Then
                        oData.Solution.Deleted = userSolution.solution.deleted
                    End If

                    nRes = oDB.SaveChanges()
                End If

            End Using

            Return nRes

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
            Return Nothing
        End Try
    End Function

    ''' <summary>
    ''' Create a User Solution
    ''' </summary>
    ''' <param name="userSolution"></param>
    ''' <returns>The new ID  of the entity</returns>
    ''' <remarks>Falta hacer validaciones</remarks>
    Public Function Create(userSolution As UserSolutionVO) As Integer
        Try
            Me.checkAccess("CREATEUSERSOLUTION")
            Dim nRes As Integer = -1

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim oUserSolution As New Data.BaseModel.UserSolution
                oUserSolution.Solution = New Data.BaseModel.Solution
                oUserSolution.Permission = New Data.BaseModel.Permission

                If oUserSolution.Solution IsNot Nothing AndAlso oUserSolution.Permission IsNot Nothing AndAlso userSolution.solution IsNot Nothing Then

                    If Not String.IsNullOrEmpty(userSolution.solution.name) Then
                        oUserSolution.Solution.Name = userSolution.solution.name
                    End If
                    If Not String.IsNullOrEmpty(userSolution.solution.description) Then
                        oUserSolution.Solution.Description = userSolution.solution.description
                    End If

                    Dim oPermission As Data.BaseModel.Permission = (From c In oDB.Permissions Where c.Code = "OWN" Select c).FirstOrDefault()
                    oUserSolution.Permission = oPermission

                    Dim oProject As New Data.BaseModel.Project
                    oProject.Name = "Default Project"
                    oProject.LastUpdate = Now

                    oUserSolution.Solution.Projects.Add(oProject)

                    '' TODO: Chequear que no exista ya una solution con ese nombre. IMPORTANTE!

                    '' Obtener Usuario
                    Dim userId As Integer = getCurrentSession().userId
                    Dim oUser As Data.BaseModel.UserCompany = (From c In oDB.UserCompanies Where c.UserCompanyId = userId Select c).FirstOrDefault()
                    '' Agregarle la UserSolution
                    oUser.UserSolutions.Add(oUserSolution)
                End If
                If oDB.SaveChanges() > 0 Then
                    nRes = oUserSolution.SolutionId
                End If
            End Using

            Return nRes

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
            Return Nothing
        End Try

    End Function

    ''' <summary>
    ''' Delete a Solution
    ''' </summary>
    ''' <param name="id">SolutionId</param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Delete(id As Integer) As Integer
        Try
            '' BORRAR EL USER, NO EL SolutionUSER
            'Me.checkAccess("DELETEUSERSOLUTION")
            Dim nRes As Integer = -1

            Using oDB As New Data.BaseModel.BaseModelContainer("name=BaseModelContainer")

                Dim oData As Data.BaseModel.UserSolution = (From c In oDB.UserSolutions Where c.UserSolutionId = id Select c).FirstOrDefault()
                'Dim oListSolutions As New Generic.List(Of Data.BaseModel.UserSolution)

                'oListSolutions = (From c In oDB.UserSolutions Where c.UserId = oDataUser.UserId Select c).ToList()

                If oData IsNot Nothing Then
                    'If oListSolutions.Any() Then
                    '    For Each oItem As Data.BaseModel.UserSolution In oListSolutions
                    '        oItem.UserPreference.Clear()
                    '        oItem.Groups.Clear()
                    '        oDB.DeleteObject(oItem)
                    '    Next
                    'End If

                    oDB.DeleteObject(oData)
                    nRes = oDB.SaveChanges()
                End If

            End Using

            Return nRes

        Catch ex As Exception
            MainLib.Helpers.ExceptionWrapper(ex)
            Return Nothing
        End Try

    End Function

End Class